var FUploaders = Object.create(null,{}),uplist =Array(),nowup= Array(),upover=Array();
var g=0;
function addvideo(n){
	var file = FUploaders[n].file,
		DOM = FUploaders[n].DOM,
		_this = FUploaders[n];
	_this.chunks = Math.ceil(file.size / chunkSize);
	_this.uploading = 1; //1进行 0暂停 
	_this.currentChunk = 0 ;
	_this.load = 0;
	uplist.push(n);
	upload();
}

function upload(id=!1)
{	
	//id为零检测nowup数组和uplist
	if(id==0){
		if(Object.keys(FUploaders).length == upover.length){
			//文件全部完成
			console.log("文件全部完成")
			return;
		}else{
			if(uplist.length==0){
				//无任务排队
				for(x in uplist){
					if(nowup.length<at_same){
						if(nowup.indexOf(uplist[x])==-1){
							console.log("添加新的任务")
							nowup.push(uplist[x]);
							uploadChunk(uplist[x]);
						}
					}else{
						console.log("任务满")
						return;
					}
				}
			}
			if([uplist.length-nowup.length]==0){
				//有任务排队，且都正在进行
				console.log("都在进行")
				return;
			}
			if([uplist.length-nowup.length]>0){
				//有任务排队，且部分正在进行
				for(x in uplist){
					if(nowup.length<at_same){
						if(nowup.indexOf(uplist[x])==-1){
							console.log("添加新的任务")
							nowup.push(uplist[x]);
							uploadChunk(uplist[x]);
						}
					}else{
						console.log("任务满")
						return;
					}
				}
			}
		}
	}
	
	//该文件上传完成判断是否添加新文件到nowup
	if(nowup.indexOf(id)==-1 && id!=0){
		for(x in uplist){
			if(nowup.length<at_same){
				if(nowup.indexOf(uplist[x])==-1){
					nowup.push(uplist[x]);
					uploadChunk(uplist[x]);
				}
			}else{
				return;
			}
		}
	}
	
	if(id!=!1 || nowup.indexOf(id)!=-1){
		uploadChunk(id);
	}
}

function uploadChunk(id)
{	
	let file = FUploaders[id].file,
		start = FUploaders[id].currentChunk * chunkSize,
		end = start + chunkSize >= file.size ? file.size : start + chunkSize,
		blob = file.slice(start,end);
	let fd = new FormData();
	let startT;
	fd.append("file",blob);
	fd.append("chunks",  FUploaders[id].chunks);
    fd.append("chunksize", blob.size);
	fd.append('Chunkindex', FUploaders[id].currentChunk);
	fd.append('id', id);
	fd.append('act', 'upload');
	let xhr = new XMLHttpRequest();
	xhr.open('post',uploadphp);
	xhr.send(fd);
	startT = (new Date()).getTime();
	xhr.upload.onloadstart = ()=>{
		startT = (new Date()).getTime();
	}
	function onprogress(size,e){
		var nowTime = (new Date()).getTime();
			progress = parseInt( size / FUploaders[id].file.size * 100)+"%",
			speed = parseInt(e / [(nowTime - startT + 20) / 1000]),
			preTime = Math.round((FUploaders[id].file.size - size) / speed);
		FUploaders[id].DOM.item_staus_percentage.innerHTML = progress;
		FUploaders[id].DOM.item_progress_show.style.width = progress;
		FUploaders[id].DOM.item_info_intro.innerHTML = bytesTosize(size) +" / " + bytesTosize(FUploaders[id].file.size)+"&emsp;";
		FUploaders[id].DOM.item_info_speed.innerHTML = bytesTosize(speed) + "/s &emsp;";
		FUploaders[id].DOM.item_info_time.innerHTML = "除余时间 : "+secondsTotime(preTime);
	}
	xhr.onload = ()=> {
		onprogress(FUploaders[id].currentChunk * chunkSize + blob.size,blob.size);
		//成功
		if(FUploaders[id].currentChunk < FUploaders[id].chunks) {
			FUploaders[id].currentChunk++;
			if(FUploaders[id].uploading == 1 ){
				upload(id);	
			}
		} else {
			uplist.splice(uplist.indexOf(id),1);
			nowup.splice(nowup.indexOf(id),1);
			upover.push(id);
			// 文件上传完成
			FUploaders[id].DOM.item_staus_op.removeChild(FUploaders[id].DOM.item_staus_percentage);
			FUploaders[id].DOM.item_staus_op.removeChild(FUploaders[id].DOM.item_staus_pause);
				
			FUploaders[id].DOM.item_info_intro.innerHTML = "文件整理中";
			FUploaders[id].DOM.item_info_speed.innerHTML = "";
			FUploaders[id].DOM.item_info_time.innerHTML = "";
			
			let fd2 = new FormData();
			fd2.append("id",id);
			fd2.append('filename', FUploaders[id].file.name);
			fd2.append('act', 'combine');
			fd2.append("chunks",  FUploaders[id].chunks);
			let xhr2 = new XMLHttpRequest();
			xhr2.open('post',uploadphp);
			xhr2.send(fd2);
			xhr2.onreadystatechange = ()=> {
				if (xhr2.readyState == 4 && xhr2.status == 200 ) {
					FUploaders[id].DOM.item_progress_show.className = "fupload-item-upload-progress-complete";
					FUploaders[id].DOM.item_staus_op.appendChild(addelement("i","fupload-icon-success"));
					FUploaders[id].DOM.item_info_intro.innerHTML = "上传完成";

					FUploaders[id].load = 1;
					xhr2 = null;
					fd2 = null;
					upload();
				}
			}
		}
		if(FUploaders[id].uploading == 0 ){
			FUploaders[id].DOM.item_info_speed.innerHTML = FUploaders[id].DOM.item_info_intro.innerHTML;
			FUploaders[id].DOM.item_info_intro.innerHTML = "暂停中 &emsp;";
			FUploaders[id].DOM.item_info_time.innerHTML = "";
		}
				
		xhr = null;
		blob = null;
		return;
	}
	
	xhr.onprogress=(evt)=>{
		onprogress( evt.loaded + FUploaders[id].currentChunk * chunkSize,evt.loaded)
	};
	
	xhr.onerror = xhr.upload.onerror = ()=> {
		// 文件上传出错
		FUploaders[id].DOM.item_staus_op.removeChild(FUploaders[id].DOM.item_staus_percentage);
		FUploaders[id].DOM.item_staus_op.removeChild(FUploaders[id].DOM.item_staus_pause);
		FUploaders[id].DOM.item_staus_op.appendChild(addelement("i","fupload-icon-error"));
		
		FUploaders[id].DOM.item_progress_show.className = "fupload-item-upload-progress-error";
		FUploaders[id].DOM.item_progress_show.style.width = "100%";
		FUploaders[id].xhr = xhr = null;
	}
	fd = null;

	
}

function bytesTosize(data)
{	
	let unit = ["Bytes","KB","MB","GB"];
	let i = parseInt(Math.log(data)/Math.log(1024));
	return (data/Math.pow(1024,i)).toFixed(2) + " " + unit[i];
}

function secondsTotime(second)
{
	let add0 = function add0(num) {return num < 10 ? '0' + num : '' + num;};
        let hour = Math.floor(second / 3600);
        let min = Math.floor((second - hour * 3600) / 60);
        let sec = Math.floor(second - hour * 3600 - min * 60);
        return (hour > 0 ? [hour,min,sec] : [min,sec]).map(add0).join(':');
}
